#!/bin/bash
#autor jiyin@redhat.com
memberxPath=/methodResponse/params/param/value/array/data/value/struct

_memberValue() {
    [ $# -lt 2 ] && {
        echo "Usage: ${0} <member name> <xmlfile>" >&2
        return 1
    }
    local idx=1 val= mname=$1 xml=$2
    $debug echo "{Debug} mname=$mname xml=$xml" >&2

    while :; do
        val=`xmllint --xpath "string($memberxPath/member[$((idx))]/name)" $xml`
        [ "$val" = "$mname" ] && { break; }
        [ -z "$val" ] && return 1
        ((idx++))
    done

    if [ "$val" = "$mname" ]; then
        xmllint --xpath "string($memberxPath/member[$idx]/value/string)" $xml
    else
        $debug echo "{Debug} not find the member name '$mname' in $xml" >&2
    fi
}
errata2distro_and_pkg() {
    [ $# -lt 1 ] && {
        echo "Usage: ${0} <errata name>" >&2
        return 1
    }
    local method=get_base_packages_rhts
    local methodb=getErrataBrewBuilds
    local errata=$1
    local epkgInfo=.epkgInfo$$
    local ebrewInfo=.ebrewInfo$$
    local brewxPath=$memberxPath/member[2]/value/string
    local pkgver= distroverx= distrover=
    local dtype=rtt distro= pkgBuild=

    [ -f /tmp/$errata ] && {
        cat /tmp/$errata
        return 0
    }

    errataInfo $errata > $epkgInfo
    errataInfo $errata $methodb > $ebrewInfo

    #get pkg version from xml
    pkgver=$(_memberValue "version" $epkgInfo)
    echo "{Debug} pkgver=$pkgver" >&2

    #get distro version form pkg version info
    distroverx=${pkgver##*.el}; distroverx=${distroverx//_/.}
    echo "{Debug} distroverFromPkg=$distroverx" >&2

    #get distro version from xml
    distrover=$(_memberValue "rhel_version" $epkgInfo)
    distrover=${distrover#RHEL-}
    echo "{Debug} distroverFromXml=$distrover" >&2

    #if there is subversion info, use it
    [ ${#distroverx} -gt ${#distrover} ] && distrover=$distroverx

    #get distro name
    [ ${#distrover} -gt 1 ] && dtype=stb
    echo "{Debug} Distrover=$distrover, dtype=$dtype" >&2
    distrover=${distrover%.[zZ]}
    distrover=${distrover%.EUS*}
    distro=$(getLatestRHEL ${dtype} ${distrover%.[zZ]})
    test -z "$distro" && distro=$(getLatestRHEL rtt ${distrover})

    #get brewbuild name from xml
    pkgBuild=$(_memberValue "brew_build_nvr" $ebrewInfo)
    echo "{Debug} PkgBuild=$pkgBuild" >&2

    rm -f $epkgInfo $ebrewInfo
    [ -z "$distro" ] && exit 1
    [ -z "$pkgBuild" ] && exit 1

    echo "$distro" $pkgBuild | tee /tmp/$errata
}

errata2distro_and_pkg "$@"

